package table

import (
	"gitee.com/zjlsliupei/ghelp"
	"gitee.com/zjlsliupei/ndb/config"
	"gitee.com/zjlsliupei/ndb/request"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
)

type Pointer struct {
	option     config.Option
	rpcName    string
	funcName   string
	arg        ghelp.MAP
	meta       ghelp.MAP
	ginContext *gin.Context
}

func NewPointer(option config.Option, rpcName string) Pointer {
	return Pointer{
		option:   option,
		rpcName:  rpcName,
		funcName: "Pointer",
		arg:      make(ghelp.MAP),
	}
}

// SetGroupId 不超过20位，用于数据分组，必填
func (this *Pointer) SetGroupId(groupId string) *Pointer {
	this.arg["group_id"] = groupId
	return this
}

// SetFormId 表单id，必填
func (this *Pointer) SetFormId(formId string) *Pointer {
	this.arg["form_id"] = formId
	return this
}

// SetPointerId
// 用于自定义分组，如果pointer_id不为空，则表示在这个表单里的特定分组。
// 例如：数据删除采用假删除，用state为-1表示删除，但希望获取未删除数据的最新一条，
// 有两个方式：a将删除数据的pointer_id设置为state-1，这样删除数据的指针列表就会区分开。b（不推荐）将未删除数据的pointer_id设置为state-0，这样state-0的队列是单独的
func (this *Pointer) SetPointerId(pointerId string) *Pointer {
	this.arg["pointer_id"] = pointerId
	return this
}

// SetOrder asc或desc，默认desc
func (this *Pointer) SetOrder(order string) *Pointer {
	this.arg["order"] = order
	return this
}

// SetLimit 返回几条，默认1
func (this *Pointer) SetLimit(limit int64) *Pointer {
	this.arg["limit"] = limit
	return this
}

// SetFields 指定返回的字段，不填为全部字段
func (this *Pointer) SetFields(fields []string) *Pointer {
	this.arg["fields"] = fields
	return this
}

// AutoMeta 自动设置meta，根据gin的上下文来解析，meta; 如果同时使用了Meta优先以Meta为准
func (this *Pointer) AutoMeta(c *gin.Context) *Pointer {
	_c := c.Copy()
	this.ginContext = _c
	return this
}

// SetMeta 设置meta
func (this *Pointer) SetMeta(meta ghelp.MAP) *Pointer {
	this.meta = meta
	return this
}

func (this *Pointer) Do() (gjson.Result, error) {
	req := request.NewRequest(this.option.Addr)
	req.FuncName(this.funcName)
	req.RpcName(this.rpcName)
	req.AutoMeta(this.ginContext)
	req.SetMeta(this.meta)
	return req.Do(this.arg)
}
